package cn.libinal.scloud.base.entity;

import cn.libinal.scloud.base.common.entity.JpaBaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Set;

/**
 * @author libinal
 * created at 2018/11/4 15:25
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Entity
@Table(name = "sys_role")
public class Role extends JpaBaseEntity {

    private static final long serialVersionUID = 7080876867885964845L;
    /**
     * 角色名
     */
    @Column(name = "role_name", length = 100, nullable = false, unique = true)
    private String name;

    /**
     * 角色英文名，大写
     */
    @Column(name = "role_sn", length = 100, nullable = false, unique = true)
    private String sn;

    /**
     * 优先级
     */
    @Column(name = "priority")
    @Min(0)
    private Integer priority;

    /**
     * 描述
     */
    @Column(name = "description", length = 200)
    private String description;

    /**
     * 菜单列表
     */
    @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
    @JoinTable(
            name = "sys_role_menu",
            joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "menu_id", referencedColumnName = "id")
    )
    @OrderBy("priority")
    @JsonIgnore
    private Set<Menu> menus = Sets.newLinkedHashSet();

    @ManyToMany(cascade = {CascadeType.REFRESH}, fetch = FetchType.EAGER)
    @JoinTable(
            name = "sys_role_permission",
            joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id")
    )
    @JsonIgnore
    private Set<Permission> permissions = Sets.newLinkedHashSet();
}
